import { Component, OnInit, Injector } from '@angular/core';
import { SignalRService } from '../../core/service/singnalr-service';
import { NzModalService, NzMessageService, UploadFile } from '../../../../node_modules/ng-zorro-antd';
import { HttpService, DrillFormControl, FieldType, SystemFormControl, KeyValueOutput, LoadRemoteDataType } from '../..';
import { Router, ActivatedRoute } from '../../../../node_modules/@angular/router';
import { FormGroup, FormBuilder, Validators } from '../../../../node_modules/@angular/forms';
import { Observable, Observer } from '../../../../node_modules/rxjs';
import { map } from '../../../../node_modules/rxjs/operators';
import { HttpClient } from '../../../../node_modules/@angular/common/http';

@Component({
  selector: 'app-drill-table-content',
  templateUrl: './drill-table-content.component.html',
  styleUrls: ['./drill-table-content.component.scss']
})
export class DrillTableContentComponent implements OnInit {
  // recordid
  recordId = 0;
  recordFlowId = 0;
  // 审核数据的流程下标
  reViewIndex = 0;

  currentIndex;
  // fileList = new Array<RecordFormUpLoadFile>();
  fileList = {};
  _focusEntity = {};


  get focusEntity(): any {
    return this.getEntityFromFormGroup(this.validateForm, this._focusEntity);
  }

  set focusEntity(input: any) {
    this.setEntityToFormGroup(this.validateForm, input);
    this._focusEntity = input;
  }

  get getCurrentIndex(): number {
    return this.currentIndex > 0 ? this.currentIndex - 1 : 0;
  }

  // 服务等内容
  httpService: HttpService;
  message: NzMessageService;
  fb: FormBuilder;
  nzModalService: NzModalService;
  validateForm: FormGroup;
  validateForm_sp: FormGroup;
  route: ActivatedRoute;
  router: Router;
  nghttp: HttpClient;
  location: Location;


  /**
    * 组件初始化
    */
  isSpinning = false;
  /**
 * 初始化订阅
 */
  GetDataObserver: Observable<any>;
  /**
 * 表单配置信息
 */
  arSystemFormControls: Array<DrillFormControl> = new Array<DrillFormControl>();
  arTableFormControls: Array<Array<DrillFormControl>> = new Array<Array<DrillFormControl>>();



  _pKeyFieldValue = 0;

  flowRecordOutput: any;
  opinion = '';

  arLogHistory = new Array<any>();

  constructor(injector: Injector,
    private signalrService: SignalRService,
    public madol: NzModalService) {
    // 注入服务组件等
    this.httpService = injector.get(HttpService);
    this.message = injector.get(NzMessageService);
    this.fb = injector.get(FormBuilder);
    this.nzModalService = injector.get(NzModalService);
    this.route = injector.get(ActivatedRoute);
    this.router = injector.get(Router);
    this.validateForm = this.fb.group({});
    this.nghttp = injector.get(HttpClient);
    // this.location = injector.get(Location);
    // 数据内容处理
    this.isSpinning = true;
    this.iniObserable();
    // this.signalrService.goToNextStep.subscribe(e => {
    //   if (this.recordId === e) {
    //     this.goToSept(this.currentIndex + 1);
    //   }
    // });
  }

  ngOnInit() {
    this.route.queryParamMap
    .pipe(map(params => params.get('id') || null))
    .subscribe(e => {
      this.recordId = Number(e);
      if (!this.recordId) {
        this.message.error('无法确定主键信息!');
      } else {
        this.GetDataObserver.subscribe(sb => {
          this.currentIndex = this.flowRecordOutput['currentStep'];
        });
      }
    });
  }

  /**
   * 用于初始化，显示其他步骤数据内容的初始化。
   */
  iniObserable() {
    const this1 = this;
    this.GetDataObserver = Observable.create(async function (observer: Observer<any>) {
      // 获取表单数据
      const res = await this1.httpService
        .get<any>(`DrillRecord/GetRecordFlowForm?recordId=${this1.recordId}
        &currentIndex=${this1.currentIndex !== undefined ? this1.currentIndex : 0}`);
      this1.flowRecordOutput = res;
      // 已经完成的演练，初始化演练时间线信息
      // if (this1.flowRecordOutput.drillStatus === 2 && this1.arLogHistory.length === 0) {
      //   this1.arLogHistory = await this1.httpService
      //     .get<any>(`DrillRecord/GetDrillRecordHistory?recordId=${this1.recordId}`);
      // }
      this1.recordFlowId = res.recordFlowId;
      this1.setFormAndGetDataList(res.drillFormOutputs, observer);
      this1.reViewIndex = res.reViewIndex;
      // if (res.reViewIndex > 0) {
      //   await this1.iniPreviewContent(this1, res);
      // }
    });
  }

  /**
  * 根据设置信息初始化表单、查询、数据格式化内容、并获取数据。
  * @param systemFormControl 系统设置信息
  */
  protected async setFormAndGetDataList(systemFormControl: Array<DrillFormControl>, observer: Observer<any>) {
    this.arSystemFormControls = systemFormControl == null ? [] : systemFormControl;
    let maxRowIndex = 0;
    // 获取最大行。
    this.arSystemFormControls.forEach(e => {
      const maxValue = e.inputRowIndex >= e.labelRowIndex ? e.inputRowIndex : e.inputRowIndex;
      if (maxValue > maxRowIndex) {
        maxRowIndex = maxValue;
      }
    });
    // 根据最大行，重新排序列表
    for (let i = 1; i <= maxRowIndex; i++) {
      const findResult = this.arSystemFormControls
        .filter(e => (e.inputRowIndex === i || e.inputRowIndex === i) && e.showInForm)
        .sort(e => e.lableColIndex);
      if (findResult) {
        this.arTableFormControls.push(findResult);
      }
    }
    //
    this.arSystemFormControls
      .filter(e => e.inputRowIndex === 0 || e.inputRowIndex === 0)
      .forEach(e => {
        if (this.arTableFormControls.filter(e1 => e1.filter(s => s.fieldName === e.fieldName).length !== 0).length === 0) {
          this.arTableFormControls.push(new Array<DrillFormControl>(e));
        }
      });
    // 根据表单设置，初始化实体。
    for (const i of Object.keys(this.arSystemFormControls)) {
      const index = parseInt(i, 0);
      const fieldName = this.arSystemFormControls[index].fieldName;
      const entity = {};
      const formControl = this.arSystemFormControls[index];
      switch (formControl.fieldType) {
        case FieldType.Number:
          this.focusEntity[fieldName] = 0;
          break;
        case FieldType.Toggle:
          this.focusEntity[fieldName] = false;
          break;
        default:
          this.focusEntity[fieldName] = '';
          break;
      }

      if (formControl.remoteData &&
        (formControl.loadRemoteDataType === null || formControl.loadRemoteDataType === LoadRemoteDataType.LoadAll)) {
        const remoteurl = this.arSystemFormControls[index].remoteData;
        const dataResult =
          await this.httpService
            .get<Array<KeyValueOutput>>(
              remoteurl.indexOf('{PID}') !== -1
                ? `${remoteurl.replace('{PID}', this._pKeyFieldValue.toString())}`
                : `${this.arSystemFormControls[index].remoteData}`);
        if (Number(entity[fieldName])) {
          dataResult.forEach(e => e.dValue = parseInt(e.dValue, 0));
        } else if (Boolean(entity[fieldName])) {
          dataResult.forEach(e => e.dValue = Boolean(e.dValue));
        }
        this.arSystemFormControls[index].fieldData = dataResult;
      }
    }
    // 根据log信息，获取非文件信息
    if (this.flowRecordOutput.dataJson) {
      const dataSource = JSON.parse(this.flowRecordOutput.dataJson);
      for (const pName of Object.keys(dataSource)) {
        if (this.focusEntity[pName] !== undefined) {
          this.focusEntity[pName] = dataSource[pName];
        }
      }
    }

    // 根据log信息，获取文件信息
    if (this.flowRecordOutput.fileJson) {
      const dataSource = JSON.parse(this.flowRecordOutput.fileJson);
      for (const pName of Object.keys(dataSource)) {
        if (this.focusEntity[pName] !== undefined) {
          this.focusEntity[pName] = dataSource[pName];
        }
      }
    }

    // 根据表单设置，初始化验证内容。
    this.validateForm = this.iniFormGroup(this.arSystemFormControls);
    this.isSpinning = false;
    observer.next(1);
  }

  /**
* 从formgroup中获取值到传输模型
*
* @protected
* @param {FormGroup} fb
* @param {T} entity
* @returns {T}
* @memberof NgZorroPageBaseComponent
*/
  protected getEntityFromFormGroup(fb: FormGroup, entity: any): any {
    for (const key of Object.keys(fb.controls)) {
      entity[key] = fb.controls[key].value;
    }
    return entity;
  }

  /**
   * 模型值复制到formgroup
   *
   * @protected
   * @param {FormGroup} fb
   * @param {T} entity
   * @returns {*}
   * @memberof NgZorroPageBaseComponent
   */
  protected setEntityToFormGroup(fb: FormGroup, entity: any): FormGroup {
    for (const key of Object.keys(entity)) {
      if (fb.controls[key]) {
        fb.controls[key].setValue(entity[key]);
      }
    }
    return fb;
  }
  /**
   * 根据设置初始化表单信息
   * @param input 系统表单设置
   */
  protected iniFormGroup(input: Array<SystemFormControl>): FormGroup {
    const group = {};
    if (input) {
      input.forEach(e => {
        // 初始化上传文件组件
        if (e.fieldType === FieldType.Upload) {
          // this.fileList.push(new RecordFormUpLoadFile(e.fieldName, new Array<UploadFile>()));
          this.fileList[e.fieldName] = new Array<UploadFile>();
        }
        const arValids = [],
          controlConfig = [];
        controlConfig.push(null);
        if (e.isRequired) {
          arValids.push(Validators.required);
        }
        if (e.minLength) {
          arValids.push(Validators.minLength(e.minLength));
        }
        if (e.maxLength) {
          arValids.push(Validators.maxLength(e.maxLength));
        }
        if (e.remoteValid) {
          controlConfig.push({
            validators: arValids,
            updateOn: 'blur',
            // asyncValidators: [this.remoteAsyncValidator(e.fieldName, e.remoteValid)]
          });
        } else {
          controlConfig.push(arValids);
        }
        group[e.fieldName] = controlConfig;
      });
    }
    // 审批意见
    group['opinion'] = [null, []];
    const formGroup = this.fb.group(group);
    return formGroup;
  }
  goToSept(index: number) {
    this.isSpinning = true;
    this.currentIndex = index;
    this._focusEntity = {};
    // this._focusEntity_sp = {};
    this.arSystemFormControls = [];
    // this.arSystemFormControls_sp = [];
    this.arTableFormControls = [];
    // this.arTableFormControls_sp = [];
    this.validateForm = this.fb.group({});
    this.GetDataObserver.subscribe(sb => {
      this.isSpinning = false;
    });
  }
}
